<?php
class collection_collect_item extends collection_collect_abstract {
		
	public function getPages() {
		$response = $this->getResponse();
		$this->_pages = array();
		if(1 && $pItem = $this->get('exp_pagelist')) {
			$_area = $response;
			$pArea = $this->get('exp_page');
			if($pArea && preg_match("#$pArea#isU", $response, $area)) {
				$_area = $area[1];
			}
			if(preg_match_all("#$pItem#isU", $_area, $items)) {
				foreach($items[1] as $page) {
					$this->_pages[] = $this->setFullLink($page);
				}
			}
		}
		if($this->get('index_as_first')) {
			array_unshift($this->_pages, $this->_row->getUrl());
		}
		return $this->_pages;
	}
	
	public function Collect() {
		if(!isset($this->_pages[$this->getPage()])) {
			throw new collection_exception("URL IS EMPTY.");
		}
		$url = $this->_pages[$this->getPage()];
		$response = $this->getResponse($url);
		
		if(!($eItem = $this->get('exp_item'))) {
			throw new collection_exception("Regular Expression of Item Matched is Empty.");
		}
		if(!($mLink = intval($this->get('matched_link')))) {
			throw new collection_exception("Matched Index of Link is Empty.");
		}
		$eArea = $this->get('exp_area');
		$mTitle = intval($this->get('matched_title'));
		$mDescription = intval($this->get('matched_description'));
		try {			
			$_area = $response;
			if($eArea && preg_match("#$eArea#isU", $response, $area)) {
				$_area = $area[1];
			}
			if(!preg_match_all("#$eItem#isU", $_area, $items)) {
				throw new collection_exception("Item can not be Matched: $url");
			}
			$list = array();
			foreach($items[0] as $key => $v) {
				if(!isset($items[$mLink])) continue;
				$link = $this->setFullLink($items[$mLink][$key]);
				$title = ($mTitle && isset($items[$mTitle])) ? trim($items[$mTitle][$key]) : '';
				$description = ($mDescription && isset($items[$mDescription])) ? $items[$mDescription][$key] : '';
				$_key = system_encrypt::shortUrl($link);
				$list[$_key] = array('key' => $_key, 'title' => $title, 'description' => $description, 'url' => $link);
			}
			
			return $list;
		} catch (Exception $ex) {
			throw $ex;
		}
	}
}
